package com.lhy.wanandroid.model.api;

import android.webkit.URLUtil;

import com.lhy.demo.common.MyApplication;
import com.lhy.util.CommonUtil;
import com.xiaojianjun.wanandroid.model.api.ApiService;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;



/**
 * @author chenzj
 * @Title: NetManager
 * @Description: 类的描述 -
 * @date 2017/3/1 16:21
 * @email admin@chenzhongjin.cn
 */
public enum NetManager {

    INSTANCE;

    private ApiService apiService;

    private final String BASE_URL = "https://www.wanandroid.com";

    public void initShopClient() {
        OkHttpClient.Builder mOkHttpClient = new OkHttpClient.Builder();
        Retrofit.Builder mRetrofit = new Retrofit.Builder();
        setCommonSetting(mOkHttpClient, mRetrofit, BASE_URL);
//        mShopClient = mRetrofit.client(mOkHttpClient.build()).build().create(ShopClient.class);

        apiService=mRetrofit.client(mOkHttpClient.build()).build().create(ApiService.class);
    }

    private void setCommonSetting(OkHttpClient.Builder okhttpBuilder, Retrofit.Builder retrofitBuilder, String hostUrl) {
        setCommonSetting(okhttpBuilder, retrofitBuilder, hostUrl, 10, 10, 10);
    }

    private void setCommonSetting(OkHttpClient.Builder okhttpBuilder, Retrofit.Builder retrofitBuilder, String hostUrl,
                                  int conTimeout, int writeTimeout, int readTimeout) {
        if (hostUrl!=null){
            if (!URLUtil.isValidUrl(hostUrl)) {
                throw new IllegalArgumentException("please setup the validUrl");
            } else {
                retrofitBuilder.baseUrl(hostUrl);
            }
        }else {
            retrofitBuilder.baseUrl("");
        }
        retrofitBuilder.addConverterFactory(GsonConverterFactory.create());
//        retrofitBuilder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());

        okhttpBuilder.connectTimeout(conTimeout, TimeUnit.SECONDS);
        okhttpBuilder.writeTimeout(writeTimeout, TimeUnit.SECONDS);
        okhttpBuilder.readTimeout(readTimeout, TimeUnit.SECONDS);


        /**
         * 设置没有网络的情况下，
         *  的缓存时间
         *  通过：addInterceptor 设置
         */
        okhttpBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!CommonUtil.isNetworkAvailable(MyApplication.getInstance())) {
                    int maxStale =  24 * 60; // 离线时缓存保存4周,单位:秒
                    CacheControl tempCacheControl = new CacheControl.Builder()
                            .onlyIfCached()
                            .maxStale(maxStale, TimeUnit.SECONDS)
                            .build();
                    request = request.newBuilder()
                            .cacheControl(tempCacheControl)
                            .build();
                }
                return chain.proceed(request);
            }
        })
        /**
         * 设置在有网络的情况下的缓存时间
         *  在有网络的时候，会优先获取缓存
         * 通过：addNetworkInterceptor 设置
         */
        .addNetworkInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response originalResponse = chain.proceed(request);
                int maxCacheTimeSecond = 120;    // 在线缓存,单位:秒
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, max-age=" + maxCacheTimeSecond)
                        .build();
            }
        })
        /**
         * 声明文件缓存地址和大小  10M
         */
        .cache(new Cache(MyApplication.getInstance().getCacheDir(),10*1024*1024))
        ;


    }

    public ApiService getApiService(){
        return apiService;
    }
}
